package com.kws.tool.util;

import com.kws.tool.exception.EsignDemoException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author :yxy
 * @date : 2024/12/9
 */
public class EQBUtil {
    /***
     * 获取文件MD5的二进制数组（128位）
     * @return
     */
    public static String getFileMD5Bytes128(MultipartFile file) throws EsignDemoException {
        InputStream fis = null;
        byte[] md5Bytes = null;
        try {
            fis=file.getInputStream();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md5.update(buffer, 0, length);
            }
            md5Bytes = md5.digest();
            fis.close();
        } catch (FileNotFoundException e) {
            EsignDemoException ex = new EsignDemoException("文件找不到", e);
            ex.initCause(e);
            throw ex;
        } catch (NoSuchAlgorithmException e) {
            EsignDemoException ex = new EsignDemoException("不支持此算法", e);
            ex.initCause(e);
            throw ex;
        } catch (IOException e) {
            EsignDemoException ex = new EsignDemoException("输入流或输出流异常", e);
            ex.initCause(e);
            throw ex;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    EsignDemoException ex = new EsignDemoException("关闭文件输入流失败", e);
                    ex.initCause(e);
                    throw ex;
                }
            }
        }
        return new String(Base64.encodeBase64String(md5Bytes));
    }

}
